//
//  HZMallGoodsListViewController.m
//  app
//
//  Created by 刘华舟 on 15/5/20.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZMallGoodsListViewController.h"
#import "HZMallSearchViewController.h"
#import "HZMallSearchResultViewController.h"
#import "HZGoodsDetailViewController.h"
#import "SNWXVoiceTestViewController.h"

#import "HZImageSourceConstant.h"
//views
#import "HZSearchTextField.h"
#import "HZCollectionView.h"
#import "HZGoodsColViewCell.h"
#import "HZTableView.h"
#import "HZGoodsTabViewCell.h"
#import "Mytoast.h"
#import "HZOrderGoodsEmptyView.h"
#import "HZCategoryGoodsListHeadView.h"
//models
#import "HZCategoryGoodsListData.h"
#import "HZRemoteResult.h"
//categeies
#import "UIImage+Conveniently.h"
//tools
#import "HZMallHttpManager.h"
#import "HZMallSqlDataManager.h"

static const NSInteger kMallHomeLabelHeight = 60;
static NSString * const kMallSearchText = @" 搜索商品";



static const NSInteger kHZTableViewTag = 4002;

@interface HZMallGoodsListViewController()<UITableViewDataSource, UITableViewDelegate,HZMallFindSearchNaviBarDelegate>

@property (strong, nonatomic) UIButton *backBtn;


@property (strong, nonatomic) HZCategoryGoodsListData *data;
@property (strong, nonatomic) HZRemoteResult *remoteData;


@property (strong, nonatomic) HZTableView *tableView;
@property (strong, nonatomic) HZCategoryGoodsListHeadView *headView;
@property (strong, nonatomic) HZOrderGoodsEmptyView *emptyView;

@end


@implementation HZMallGoodsListViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    
    self.title = @"热门商品";
    self.navigationController.navigationBar.hidden = NO;
    self.view.backgroundColor = HZ_MALL_MAIN_THEME_WHITE;
    
    
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.barTintColor = nil;
    self.navigationController.navigationBar.translucent = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //backBtn
    self.backBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP],
                                                            [self.ubo uw:kMallHomeLabelHeight uh:kMallHomeLabelHeight])];
    [self.backBtn setImage:[UIImage imageNamed:kImageMallArrowBackReturnRed] forState:UIControlStateNormal];
    self.backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.backBtn addTarget:self action:@selector(backBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backBtn];
    
    
    HZCategoryGoodsListHeadView *firstHeaderView = [[HZCategoryGoodsListHeadView alloc] initWithFrame:CGRectOf([self.ubo fx:UB_TOP fy:UB_TOP], [self.ubo fw:UB_WIDTH uh:kMainViewHeight])];
    [firstHeaderView showTopPages:self.data.topBanners bottomPages:self.data.bottomBanners imageKey:APIKEY_mall_pic];
    firstHeaderView.pageTappedCaller = [UBTargetCaller of:self action:@selector(imageViewDidClick:)];
    firstHeaderView.sDelegate = self;
    self.headView = firstHeaderView;
    
    //添加tableView
    self.tableView = [[HZTableView alloc] initWithFrame:CGRectOf(CGPointMake(0, 0),
                                                                 [self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT]) style:UITableViewStylePlain];
    self.tableView.backgroundColor = HZ_CLEAR_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableHeaderView = self.headView;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(self.navigationAndStatusBarHeight, 0, 0, 0);
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(self.navigationAndStatusBarHeight, 0, 0, 0);
    self.tableView.footerRefreshController = [[UIRefreshFooterController alloc] initWithTableView:self.tableView caller:[UBTargetCaller of:self action:@selector(loadMoreData)]];
    self.tableView.nothingRefreshView = [[UIRefreshNotingRefreshView alloc] initWithView:self.tableView viewController:self tryAgain:@selector(loadGoodsListDataWithPage:)];
    
    self.tableView.tag = kHZTableViewTag;
    
    [self.view addSubview:self.tableView];
    
    [self.tableView.nothingRefreshView showLoadingMsg:nil errorMsg:@"加载失败，点击重试"];
    
    self.emptyView = [[HZOrderGoodsEmptyView alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP], [self.ubo fw:UB_WIDTH fh:UB_HEIGHT])];
    [self.emptyView hide];
    [self.view addSubview:self.emptyView];
    
    self.remoteData = [HZRemoteResult target:self action:@selector(finishedLoadGoodsSearchData:)];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //设置最终状态
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.barTintColor = nil;
    self.navigationController.navigationBar.translucent = YES;
    

    
    if (self.actName.length) {
        self.title = self.actName;
    }
    
    if (self.data == nil) {
        [self loadGoodsListDataWithPage:@"0"];
    }
    
    
    
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    
}

#pragma mark 刷新商品列表视图
- (void)refreshGoodsListView{

    self.tableView.tableHeaderView = self.headView;
    [self.tableView reloadData];

}

#pragma mark 加载数据
- (void)loadGoodsListDataWithPage:(NSString *)page{
    
    if (self.actID == nil || self.actID.length == 0) {
        self.actID = @"-1";
    }
    
    if ([page isKindOfClass:[NSString class]]) {
        if (page == nil || page.length==0) {
            page = @"1";
        }
    }else{
        page = @"1";
    }
    
    
    
    
    HZMallHttpManager *httpManager = [HZMallHttpManager shareHttpRequestMananger];
    NSDictionary *params = @{APIKEY_mall_act_id:self.actID,
                             APIKEY_mall_page:page};
    [httpManager loadCategoryGoodsListWithParams:params result:self.remoteData];
}

#pragma mark 加载更多数据
- (void)loadMoreData{
    
    if (self.data.noMoreData) {
        [self.tableView endRefreshingAll];
        [MyToast showDefaultBottonWithText:@"已显示全部商品"];
    }else{
        NSDictionary *params = @{APIKEY_mall_act_id:self.actID,
                                 APIKEY_mall_page:[NSString stringWithFormat:@"%d", [self.data.pageNum integerValue]+1]};
        HZMallHttpManager *httpManager = [HZMallHttpManager shareHttpRequestMananger];
        [httpManager loadMoreCategoryGoodsListWithParams:params result:self.remoteData];
    }
    
}

#pragma mark 完成加载数据
- (void)finishedLoadGoodsSearchData:(HZRemoteResult *)result{
    [self.tableView endRefreshingAll];
    
    
    if (result.response.status == JKResponseServerError || result.response.status == JKResponseLocalError) {
        [self.tableView.nothingRefreshView activeStop];

        [self.emptyView hide];
    }else if (result.response.status == JKResponseOK || result.response.status == JKResponseTail) {
        
        [self.tableView.nothingRefreshView remove];

        self.data = result.info;
        
        HZCategoryGoodsListHeadView *headerView = (HZCategoryGoodsListHeadView *)self.headView;
        [headerView showTopPages:self.data.topBanners bottomPages:self.data.bottomBanners imageKey:APIKEY_mall_ad_pic];
        headerView.pageTappedCaller = [UBTargetCaller of:self action:@selector(imageViewDidClick:)];
        
        [self.emptyView hide];
        
        if (self.data) {
            if (self.data.goodsArray.count == 0) {
                [self.emptyView showWithMessage:@"抱歉，暂无此类商品!"];
            }
        }else{
            [self.tableView.nothingRefreshView remove];
            if(result.response.status == JKResponseTail){
                [self.emptyView showWithMessage:@"抱歉，暂无此类商品!"];
            }else{
                [self.emptyView showWithMessage:result.response.message];
            }
        }
    }else{
        [self.tableView.nothingRefreshView remove];

        if(result.response.status == JKResponseTail){
            [self.emptyView showWithMessage:@"抱歉，暂无此类商品!"];
        }else{
            [self.emptyView showWithMessage:result.response.message];
        }
        
    }
    
    [self refreshGoodsListView];

    
}
#pragma mark 点击返回
- (void)backBtnOnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark 点击搜索框
- (void)mallFindSearchTap{
    HZMallSearchViewController *mallSearchVC = [[HZMallSearchViewController alloc] init];
    [self.navigationController pushViewController:mallSearchVC animated:YES];
}

#pragma mark 点击语音搜索按钮
- (void)mallFindVoiceSearchTap{
    SNWXVoiceTestViewController * wxVoiceVC = [[SNWXVoiceTestViewController alloc] init];
    wxVoiceVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:wxVoiceVC animated:YES];
}

#pragma mark 点击搜索关键字分类
- (void)cellTagOnClick:(NSString *)keyword{

    //保存搜索历史
    HZMallSqlDataManager *sqlManager = [HZMallSqlDataManager defaultManager];
    [sqlManager updateMallSearchHistoryCacheWithData:keyword];

    
    //跳转到搜索列表页面
    HZMallSearchResultViewController *mallGoodsListVC = [[HZMallSearchResultViewController alloc] init];
    mallGoodsListVC.keyword = keyword;
    mallGoodsListVC.backOnce = YES;
    [self.navigationController pushViewController:mallGoodsListVC animated:YES];
}

#pragma mark 点击顶部图片
- (void)imageViewDidClick:(id)sender{
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    
    if (textField.text.length == 0) {
        [MyToast showDefaultBottonWithText:@"请输入您要搜索的商品"];
    }else{
        self.remoteData.info = nil;
        self.data = nil;
        [self loadGoodsListDataWithPage:@"0"];
    }
    
    
    return YES;
}




#pragma mark UITableViewDelegate UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.data.goodsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HZGoodsTabViewCell *cell = [HZGoodsTabViewCell cellWithTableView:(HZTableView *)tableView];
    cell.model = [self.data fetchCellModelAtRow:indexPath.row];
    cell.targetCallerTapTag = [UBTargetCaller of:self action:@selector(cellTagOnClick:)];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [HZGoodsModel tableViewCellHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
    //跳到商品详情页面
    
    HZGoodsModel *model = [self.data fetchCellModelAtRow:indexPath.row];
    HZGoodsDetailViewController *detailVC = [[HZGoodsDetailViewController alloc] init];
    detailVC.shopID = model.shopID;
    detailVC.productID = model.productID;
    
    [self.navigationController pushViewController:detailVC animated:YES];

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

}




@end
